var gamejs = require('gamejs');
var soundjs = require('js/soundmanager');
var lturretjs = require("js/turrets/laserTurret");
var sturretjs = require("js/turrets/slowingTurret");
var mturretjs = require("js/turrets/missleTurret");
var radarjs = require('js/radar');
/**
 * Creates a match
 */
var Match = exports.Match = function() {
	this.choice = "nothing";
	this.score = 0;
	this.credits = 1000;
	this.fullHealth = 50000; 
	this.health = 50000;   
	this.currentMap = 0; 
	this.cachedScore = -1;
	this.scoreSurface = null;
	this.creditSurface = null;
	this.menu = null;
	this.font = new gamejs.font.Font('20px ubuntu, sans-serif');
	this.currentSoundManager = new soundjs.SoundManager();
	this.getSoundManager().playNight();
	this.gameover = gamejs.image.load('resources/images/gameover.png');
	this.upgrade = gamejs.image.load('resources/images/upgrade.png');
}

/**
* Return current map
* @return
*/
Match.prototype.getMap = function(){
	return this.currentMap;
}

/**
* Return current soundmanager
*/
Match.prototype.getSoundManager = function(){
	return this.currentSoundManager;
}

/**
* Set current map
* @param {Map}
*/
Match.prototype.setMap = function(map){
	this.currentMap = map;
}

/**
* Set current menu
* @param {obj}
*/
Match.prototype.setMenu= function(obj){
	this.menu = obj;
}

/**
 * Decrease health by one point
 *
 * @param {undefined|number} hitpoint Removes one health point if undefined, or the specified amount
 *
 * @return {number} The remaining health points
 */
Match.prototype.decreaseHealth = function(hitpoint) {
	if (typeof hitpoint === "undefined"){
		this.health--;
	} 
	else {
		if ( typeof hitpoint === "number" && hitpoint > 0 ){
			this.health -= hitpoint;   
		}
		else{
			throw "Invalid hitpoint value";
		}         
	}
	
	return this.health;
}

/**
 * Change credit amount
 *
 * @param {undefined|number} amount change credit by amount
 *
 * @return {number} The remaining credit points
 */
Match.prototype.changeCredit = function(amount) {
	if ( typeof amount === "number" ){
		this.credits += amount;   
	}
	else{
		throw "Invalid credit value";
	}         
	
	return this.credits;
}

/**
 * Get credit amount
 *
 * @return {number} The remaining credit points
 */
Match.prototype.getCredit = function(amount) {   
	
	return this.credits;
}

/**
 * Change score amount
 *
 * @param {undefined|number} amount change score by amount
 *
 * @return {number} The remaining score points
 */
Match.prototype.changeScore = function(amount) {
	if ( typeof amount === "number" ){
		this.score += amount;   
	}
	else{
		throw "Invalid score value";
	}         
	
	return this.score;
}

/**
 * Update the data in the game
 */
Match.prototype.update = function(msDuration){ 
	if(this.health>0){
/*		var events = gamejs.event.get();
	    for(i = 0; i< events.length; i++){
	       if (events[i].type === gamejs.event.MOUSE_UP) {
	    	   this.getMap().addTurret(new sturretjs.slowingTurret(this, events[i].pos))
	       } else if (events[i].type === gamejs.event.MOUSE_WHEEL) {
	    	   this.getMap().addRadar(new radarjs.Radar(this, events[i].pos))
	       }
	    }*/
		this.eventDispatcher();
		this.getMap().update(msDuration);
		this.getMap().getEnemies().update(msDuration);
		this.getMap().getRadars().update(msDuration);
		this.getMap().getTurrets().update(msDuration);
	}
}

/**
 * Draw the overlay information
 * @param {gamejs.surface} where to draw
 */
Match.prototype.draw = function(display_surface){ 
	if(this.health>0){
		this.getMap().draw(display_surface);
		this.getMap().getEnemies().draw(display_surface);		
		this.getMap().getRadars().draw(display_surface);
		this.getMap().getObstacles().draw(display_surface);
		this.getMap().getTurrets().draw(display_surface);
		
		scoreSurface = this.font.render("Score: " +this.score, "#fff");
		creditSurface = this.font.render("Credit: " +this.credits, "#fff"); 
	    gamejs.draw.rect(display_surface, "rgb("+Math.round(255 * ( this.fullHealth - this.health) / this.fullHealth)+", "+Math.round(255 * this.health / this.fullHealth)+", 0)", new gamejs.Rect([26 + 16, 19, Math.max(0, this.health/200), 4]), 0);
	    display_surface.blit(scoreSurface, [650, 8]);
	    display_surface.blit(creditSurface, [450, 8]);
	    //lateral bar
	    //gamejs.draw.rect(display_surface,"#cccccc",new gamejs.Rect([0,0],[50,480]));
	    
	    /*Icon to manage the build of new structures*/
		var dim = 40; //icons'size
		if(this.menu ==null){
			var image;
			image = gamejs.image.load("resources/images/laserturret.png");
			image = gamejs.transform.scale(image,[image.getSize()[0]*0.8, image.getSize()[1]*0.8]);
			display_surface.blit (image, [5,50]);
			image = gamejs.image.load("resources/images/sat.png");
			image = gamejs.transform.scale(image,[image.getSize()[0]*0.8, image.getSize()[1]*0.8]);
			display_surface.blit (image, [5,100]);
			image = gamejs.image.load("resources/images/missleturret.png");
			image = gamejs.transform.scale(image,[image.getSize()[0]*0.8, image.getSize()[1]*0.8]);
			display_surface.blit (image, [5,150]);
			image = gamejs.image.load("resources/images/slowingturret.png");
			image = gamejs.transform.scale(image,[image.getSize()[0]*0.8, image.getSize()[1]*0.8]);
			display_surface.blit (image, [5,200]);
			
		}else{
			display_surface.blit (this.upgrade, [5,50]);
			display_surface.blit (this.menu.menuSurface, [5,100]);
		}
		}else{
		display_surface.blit(this.gameover, [0, 0]);
	}
     
};


/**
 * Draw a popup message
 */
Match.prototype.popup = function(message) { 
	alert(message);	
};

/**
 * positionClick
 * 
 * @return {number} line number where you're clicking in menu, return -1 if you don't click anything
 */
Match.prototype.positionClick = function(coord) {
	var numOfLine = -1;
	var columnWidth = 50;
	var lineHeight = 50;
	if (coord[0] <= columnWidth) {
		numOfLine = Math.floor(coord[1] / lineHeight);
	}
	return numOfLine;
}

/**
 *eventDispatcher: function to manage the click events
 */
Match.prototype.eventDispatcher = function(){
	var dim = 40; //icons'size
	//line1: laser builder position
	//line2: radar builder position
	
	var events = gamejs.event.get();
	var curThis = this;
	events.forEach(function(event) {
		if (event.type == gamejs.event.MOUSE_UP) {
			coord=[event.pos[0],event.pos[1]];
			if (curThis.menu==null && curThis.positionClick(event.pos)==2)
				curThis.choice = "radar";
				
			else if (curThis.menu==null && curThis.positionClick(event.pos)==1)
				curThis.choice = "laser";
			
			else if (curThis.menuTurret==null && curThis.positionClick(event.pos)==3)
				curThis.choice = "missile";
			
			else if (curThis.menuTurret==null && curThis.positionClick(event.pos)==4)
				curThis.choice = "slower";
			
			else if (curThis.menuTurret==null && curThis.choice == "laser"){
				curThis.getMap().addTurret(new lturretjs.laserTurret(curThis, event.pos));
				curThis.choice = "nothing";

			}else if (curThis.menu==null && curThis.choice == "radar"){
				curThis.getMap().addRadar(new radarjs.Radar(curThis, event.pos));
				curThis.choice = "nothing";
			
			}else if (curThis.menuTurret==null && curThis.choice == "missile"){
				curThis.getMap().addTurret(new mturretjs.missleTurret(curThis, event.pos));
				curThis.choice = "nothing";
				
			}else if (curThis.menuTurret==null && curThis.choice == "slower"){
				curThis.getMap().addTurret(new sturretjs.slowingTurret(curThis, event.pos));
				curThis.choice = "nothing";
				
			}else{
				var curEvent = event;
				curThis.getMap().getTurrets().sprites().forEach(function (collision_list) {
					collision_list.click(curEvent.pos);
				});
				curThis.getMap().getRadars().sprites().forEach(function (collision_list) {
					collision_list.click(curEvent.pos);
				});
			}
		}else{
			gamejs.event.post({
                type: event.type,
                data: event.data
             })
		}//if
	});//forEach
}//eventDispatcher
